<?php


namespace app\api\controller;


use app\common\model\mk\SmsModels;
use app\common\model\mk\SmsResults;

class Sms
{
    public function smsCode(){

        $validate = new \app\common\validate\mk\Sms();
        if (!$validate->check(input())) {
            return apiError($validate->getError());
        }
        $type = input('type');
        $phone = input('phone');
        if(!isMobile($phone)) return apiError('电话号码不符合要求');
        $code =rand(100000, 999999);
        $content = '您的验证码是：' . $code . '。请不要把验证码泄露给其他人。';
        $where = [
            'phone' => $phone,
            'type' => $type
        ];
        $curTime = time();
        $result = SmsModels::where($where)->find();
        if($result){
            $time = $curTime - $result->addTime;
            if ($time < 60) {
                return apiError("60秒内不能重复获取短信验证码",400);
            }
            $res = SmsModels::where($where)->update([
                'addTime' => $curTime,
                'code' => $code
            ]);
        }else{
            $res = SmsModels::create([
                'phone' => $phone,
                'type' => $type,
                'addTime' => $curTime,
                'code' => $code
            ]);
        }
        if (! $res) {
            return apiError("服务器异常，请稍后重试",400);
        }
        $data = $this->sendSms($phone,$content);
        if (empty($data)) {
            return apiError("服务器异常，请稍后重试01",400);
        }
        if ($data['result'] != 0) {
            return apiError("服务器异常，请稍后重试02",400);
        }
        return apiSuccess("获取短信验证成功!",200);
    }

    protected function sendSms($phone, $content, $f = 0)
    {
        try {
            $sms = config('sms');
            $timestamp = date("Y-m-d H:i:s", time());
            $password = md5($sms['password'] . $timestamp);
            $content .= $sms['sign'];
            // 定义参数
            $params = [
                'username' => $sms['username'],
                'password' => $password,
                'mobiles' => $phone,
                'content' => $content,
                'timestamp' => $timestamp,
                'f' => $f
            ];
            $url = $sms['api'] . '?' . http_build_query($params);
            $receive = httpRequest($url);
            $receive = urldecode($receive);
            SmsResults::create([
                "phone" => $phone,
                "content" => $content,
                "is_flag" => $f,
                "result" => $receive,
                "add_time" => time()
            ]);
            parse_str($receive, $parameter);
            return $parameter;

        } catch (\Exception $e) {
            return false;
        }
    }

}
